package com.huilian.tool.douyin.applet.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.common.config.AppletDouYinConfig;
import com.huilian.tool.douyin.applet.service.DouYinAppletLifeService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: loong
 * @create: 2023-03-24 16:03
 **/
@Service
public class DouYinAppletLifeServiceImpl implements DouYinAppletLifeService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private AppletDouYinConfig appletDouYinConfig;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public String getDouYinAppletLifeAccessToken(String redisKey) throws Exception {
        String accessToken = (String) redisCacheTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(accessToken)) {
            JSONObject jsonObject = this.getAccessToken();
            JSONObject data = jsonObject.getJSONObject("data");
            if (data.getInteger("error_code").equals(0)) {
                accessToken = data.getString("access_token");
                redisCacheTemplate.opsForValue().set(redisKey, accessToken, 7100, TimeUnit.SECONDS);
            } else {
                throw new Exception("请求抖音小程序生活服务accessToken失败！" + jsonObject);
            }
        }
        return accessToken;
    }

    public JSONObject getAccessToken() {
        StringBuilder url = new StringBuilder("https://open.douyin.com/oauth/client_token/");
        Map<String, Object> params = new HashMap<>();
        params.put("client_key", appletDouYinConfig.getAppId());
        params.put("client_secret", appletDouYinConfig.getAppSecret());
        params.put("grant_type", "client_credential");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);
        return restTemplate.postForObject(url.toString(), entity, JSONObject.class);
    }
}
